/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package submarines.thread;

import submarines.Config;
import submarines.Player;
import submarines.PlayerManager;
import submarines.notices.NotficationManager;
import submarines.notices.Notice;
import submarines.notices.NoticePlayerQuit;

/**
 *
 * @author elad
 */
public class TimeoutChecker extends Thread {

    PlayerManager pManager;
    NotficationManager nManager;
    
    public TimeoutChecker(PlayerManager p, NotficationManager n) {
        pManager = p;
        nManager = n;
    }
    
    @Override
    public void run() {
        while (pManager.numPlayersLeft() > 1) {
            pManager.timeOut();
            
            boolean computersOnly = true;
            for (int i = 0; i < pManager.numPlayersLeft(); i++) {
                Player p = pManager.get(i);
                if (p.getType().equals(Config.HUMAN_PLAYER)) {
                    computersOnly = false;
                    break;
                }
            }
            
            if (computersOnly) {
                while (pManager.numPlayersLeft() > 1) {
                    Player p = pManager.get(0);
                    pManager.playerQuit(p);
                    
                    NoticePlayerQuit notice = new NoticePlayerQuit(p, Notice.NoticeType.PLAYER_QUIT);
                    nManager.spreadTheWord(p, p, notice);
                }
            }
            try {
                sleep(1000);
            } catch (InterruptedException ex) {
                
            }
        }
    }
    
}
